package dhee.wtqshopproject.service.impl;

import dhee.wtqshopproject.dao.UserMapper;
import dhee.wtqshopproject.entity.User;
import dhee.wtqshopproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    // 固定盐值（实验环境使用）
    private static final String FIXED_SALT = "WTQSALT";

    @Override
    @Transactional
    public void register(User user) {
        // 检查用户名是否已存在
        List<User> existUsers = userMapper.selectByUsername(user.getUsername());
        if (!existUsers.isEmpty()) {
            throw new RuntimeException("用户名已存在！");
        }

        // 密码加密处理
        String encryptedPass = encryptPassword(user.getPassword());
        user.setPassword(encryptedPass);

        // 设置默认角色和激活状态
        user.setRole("user");
        user.setIsActive(Byte.valueOf("1"));

        userMapper.zhuceUser(user);
    }

    @Override
    public User login(User user) {
        // 根据用户名查询用户
        List<User> users = userMapper.selectByUsername(user.getUsername());
        if (users.isEmpty()) {
            throw new RuntimeException("用户不存在！");
        }

        User dbUser = users.get(0);

        // 验证密码
        String encryptedInput = encryptPassword(user.getPassword());
        if (!dbUser.getPassword().equals(encryptedInput)) {
            throw new RuntimeException("密码错误！");
        }

        // 检查账户是否激活
        if (dbUser.getIsActive()!=1) {
            throw new RuntimeException("账户已被禁用");
        }

        return dbUser;
    }

    // 简化版密码加密（固定盐值）
    private String encryptPassword(String password) {
        String saltedPass = password + FIXED_SALT;
        return DigestUtils.md5DigestAsHex(saltedPass.getBytes());
    }

    @Override
    public int addUser(User user) {
        // 密码加密处理（固定盐值）
        user.setPassword(encryptPassword(user.getPassword()));
        return userMapper.insertUser(user);
    }

    @Override
    public int deleteUser(Integer id) {
        // 检查用户是否存在
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在！");
        }
        return userMapper.deleteById(id);
    }

    @Override
    public int updateUser(User user) {
        // 检查用户是否存在
        User existUser = userMapper.selectById(user.getUserId());
        if (existUser == null) {
            throw new RuntimeException("用户不存在！");
        }

        // 如果密码被修改，重新加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(encryptPassword(user.getPassword()));
        } else {
            // 保留原密码
            user.setPassword(existUser.getPassword());
        }

        return userMapper.updateUser(user);
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public List<User> findUserByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            throw new IllegalArgumentException("用户名不能为空！");
        }
        return userMapper.selectByUsername(username);
    }

    @Override
    public List<User> findAllUsers() {
        return userMapper.selectAll();
    }

    @Override
    public List<User> searchUsers(String keyword) {
        return userMapper.selectLike(keyword);
    }

    // VIP会员管理方法
    @Override
    public List<User> findAllVipUsers() {
        return userMapper.selectAllVipUsers();
    }

    @Override
    public Map<String, Object> findVipUsersByPage(int page, int pageSize) {
        // 参数验证
        if (page < 1) page = 1;
        if (pageSize < 1) pageSize = 10;

        int offset = (page - 1) * pageSize;

        List<User> vipUsers = userMapper.selectVipUsersByPage(offset, pageSize);
        int totalCount = userMapper.countVipUsers();

        int totalPages = (int) Math.ceil((double) totalCount / pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("data", vipUsers);
        result.put("currentPage", page);
        result.put("pageSize", pageSize);
        result.put("totalCount", totalCount);
        result.put("totalPages", totalPages);

        return result;
    }

    @Override
    public Map<String, Object> searchVipUsers(String keyword, int page, int pageSize) {
        if (page < 1) page = 1;
        if (pageSize < 1) pageSize = 10;

        int offset = (page - 1) * pageSize;

        List<User> searchResults = userMapper.searchVipUsers(keyword, offset, pageSize);
        int totalCount = userMapper.countSearchVipUsers(keyword);

        int totalPages = (int) Math.ceil((double) totalCount / pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("data", searchResults);
        result.put("keyword", keyword);
        result.put("currentPage", page);
        result.put("pageSize", pageSize);
        result.put("totalCount", totalCount);
        result.put("totalPages", totalPages);

        return result;
    }

    @Override
    public int getVipUserCount() {
        return userMapper.countVipUsers();
    }
}